/*
rewrite pomelo channel service
*/
let PushMessageService = function (app) {
    this.app = app;
};

PushMessageService.prototype.unicast = function(connection, messageType, message) {
    this.doCast(connection['frontendId'], messageType, message, connection['sessionId']);
};

PushMessageService.prototype.multicast = function (connections, messageType, message) {
    let serverIdsToSessionIds = {};
    let length = connections.length;
	for (let i = 0 ; i < length; i++) {
        let connection = connections[i];
        let frontendId = connection['frontendId'];
        let sessionId = connection['sessionId'];
        if (!serverIdsToSessionIds[frontendId]) {
            serverIdsToSessionIds[frontendId] = [];          
        }
        serverIdsToSessionIds[frontendId].push(sessionId);
  	}
	for (var serverId in serverIdsToSessionIds) {
		this.doCast(serverId, messageType, message, serverIdsToSessionIds[serverId]);
	}
};

PushMessageService.prototype.doCast = function (serverId, messageType, message, sessionIds) {
	this.app.rpcInvoke(serverId, {
        namespace : "user", service : "pushMessageRemote", method : "pushMessage",
        args : [messageType, message, sessionIds]}, function (error, failed) {});
};

PushMessageService.prototype.broadcast = function (messageType, message) {
    let servers = this.app.getServersByType('connector');
    let length = servers.length;
    for (let i = 0; i < length; i++) {
        this.app.rpcInvoke(servers[i].id, {
                namespace : 'user', service : 'pushMessageRemote', method : 'broadcast',
                args : [messageType, message, {
                    type: 'broadcast', userOptions: {binded: false}
                }]},
            function(error, failed) {
            }
        );
    }
};

exports.create = function (app) {
	return new PushMessageService(app);
};
